package com.df.excel_export.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.df.excel_export.common.ExcelTableManager;
import com.df.excel_export.common.ExportTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 客户端发布任务时进行链接
 */
@Component
@Slf4j
@ServerEndpoint("/export")
public class ExportTaskWebSocket {
    public static final CopyOnWriteArraySet<Session> SESSIONS = new CopyOnWriteArraySet<>();
    private static final Map<String,Session> SESSION_MAP = new HashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        try {
            SESSIONS.add(session);
            UUID uuid = UUID.randomUUID();
            SESSION_MAP.put(uuid.toString(), session);
            log.info("【WebSocket消息】有新的连接，总数为：" + SESSIONS.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session) {
        try {
            SESSIONS.remove(session);
            log.info("【WebSocket消息】连接断开，总数为：" + SESSIONS.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("【WebSocket消息】收到客户端消息：" + message);
        JSONObject jsonObject = JSON.parseObject(message);
        Integer id = jsonObject.getInteger("id");
        switch (id){
            case 1:
                sendTaskStatus(jsonObject);
                break;
            case 2:
                break;
            case 3:
                break;
        }
    }

    private void sendTaskStatus(JSONObject jsonObject) {
        JSONObject data = jsonObject.getJSONObject("data");
        String string = data.getString("type");
        if(string.equals("config")){//导表任务
            ExportTask task = ExportTask.nowTask;
            JSONObject respMsg = new JSONObject();
            respMsg.put("id",2);
            JSONObject respData = new JSONObject();
            respData.put("type","config");
            if(task==null){
                respData.put("status",0);
            }else{
                respData.put("status",1);
            }
            respMsg.put("data",respData);
            sendAllMessage(JSON.toJSONString(respMsg));
            return;
        }
        if(string.equals("protoc")){//导协议任务
            return;
        }
    }

    /**
     * 此为广播消息
     *
     * @param message 消息
     */
    public  static void sendAllMessage(String message) {
        for (Session session : SESSIONS) {
            try {
                if (session.isOpen()) {
                    session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 此为单点消息
     *
     * @param userId  用户编号
     * @param message 消息
     */
    public void sendOneMessage(String userId, String message) {
        Session session = SESSION_MAP.get(userId);
        if (session != null && session.isOpen()) {
            try {
                synchronized (session) {
                    log.info("【WebSocket消息】单点消息：" + message);
                    session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 此为单点消息(多人)
     *
     * @param userIds 用户编号列表
     * @param message 消息
     */
    public void sendMoreMessage(String[] userIds, String message) {
        for (String userId : userIds) {
            Session session = SESSION_MAP.get(userId);
            if (session != null && session.isOpen()) {
                try {
                    log.info("【WebSocket消息】单点消息：" + message);
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
